#include <Wire.h>
int ledPin = 13;

uint8_t outbuf[] = { 0, 64, 0, 0, 0, 0, 0 };
int storebuffer[199];
int cnt = 0;

void
receiveEvent (int howMany)
{
  Serial.println ("\n on recieve envet \n");
}

void
requestEvent ()
{
  Serial.println ("\n on request event \n");
}

void
setup ()
{
  pinMode (ledPin, OUTPUT);	// sets the digital pin as output
  beginSerial (19200);
  Serial.print ("setup\n");
  Wire.begin (0x52);		// join i2c bus as master
  Wire.onReceive (receiveEvent);	// register event
  Wire.onRequest (requestEvent);	// register event

  Wire.beginTransmission (0x52);	// transmit to device 0x52 
  Wire.send ( 0x40 );	// sends one byte  
  //Wire.send ( 10 );	// sends one byte 
  Wire.endTransmission ();	// stop transmitting 
}

void
loop ()
{
   Wire.beginTransmission (0x52);	// transmit to device 0x52 
  Wire.send ( 0x01 );	// sends one byte  
  Wire.endTransmission ();	// stop transmitting 
  
    Wire.requestFrom (0x52, 8);	// request data from nunchuck
    while (Wire.available ())
    {
      int c = Wire.receive ();	// receive byte as a character   
      storebuffer[cnt] = c;
      cnt++;
            storebuffer[cnt] = 9;
      cnt++;
      if (cnt > 148)
	{
	  print ();
	}
    }
    
    Wire.requestFrom (0x52, 8);	// request data from nunchuck
    while (Wire.available ())
    {
      int c = Wire.receive ();	// receive byte as a character   
      storebuffer[cnt] = c;
      cnt++;
            storebuffer[cnt] = 7;
      cnt++;
      if (cnt > 148)
	{
	  print ();
	}
    }
  Wire.beginTransmission (0x52);	// transmit to device 0x52 
  Wire.send ( 0x00 );	// sends one byte  
  Wire.endTransmission ();	// stop transmitting 

}

void
print ()
{
  int s = 0;
  digitalWrite (ledPin, HIGH);	// sets the LED on
  Serial.print ("start data dump");
  while (s < (cnt - 1))
    {
      Serial.print (storebuffer[s], DEC);
      s++;
    }
   
  Serial.println ("end data dump");
  cnt = 0;
}
